import time,os,requests

def saveVideo(filePath, index, videoUrl, fei):
    # 进入网页
    try:
        fei.browser.get(videoUrl)
    except:
        fei.browser.get(videoUrl)

    time.sleep(5)
    print(videoUrl)
    videoUrl = fei.browser.find_elements_by_css_selector('#douyin-right-container > div:nth-child(3) > div > div.leftContainer.w0R6mo9z > div.cXOuLiGd.enQDGznb.video-detail-container.newVideoPlayer.isDanmuPlayer.detailNotFullScreen > div > xg-video-container > video > source:nth-child(1)')

    if videoUrl:
        # 找到了视频元素
        videoUrl = videoUrl[0].get_attribute('src')

        print(videoUrl)
        print('---' * 50)
        # 保存视频路径
        videoName = 'video{}.mp4'.format(index)
        videoPath = filePath + '\\' + videoName
        # 拿数据
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.183',
        }

        try:
            response = requests.get(videoUrl, headers=headers)
        except:
            response = requests.get(videoUrl, headers=headers)

        try:
            with open(videoPath, 'wb') as f:
                if response.status_code == 200:
                    # 写入文件
                    f.write(response.content)
            return videoPath
        except requests.RequestException as e:
            print("下载视频失败：", e)
    else:
        # 没有找到视频元素，处理页面不存在视频的情况
        videoUrl = None  # 或者设置一个默认值，或者输出提示信息


if __name__ == '__main__':
    from tasks.init_selenium import Feigua
    fei = Feigua()
    saveVideo(1,1,1,fei)